#include "para_settings.h"

#include <QDebug>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QMessageBox>

#include "DeviceManager.h"
#include "System.h"
#include "define.h"
#include "ui_para_settings.h"
#include "user.h"
void para_settings::initMappings()
{
    m_spinBoxMap["zeroCheckIntervalDays"] = ui->spinBox_29;
    m_spinBoxMap["zeroCheckTime"] = ui->spinBox_30;
    m_spinBoxMap["stdCheckIntervalDays"] = ui->spinBox_31;
    m_spinBoxMap["stdCheckTime"] = ui->spinBox_32;
    m_spinBoxMap["calibIntervalDays"] = ui->spinBox_33;
    m_spinBoxMap["calibTime"] = ui->spinBox_34;
    m_spinBoxMap["spikeRecoveryIntervalDays"] = ui->spinBox_35;
    m_spinBoxMap["spikeRecoveryTime"] = ui->spinBox_36;
    m_spinBoxMap["cleanIntervalDays"] = ui->spinBox_37;
    m_spinBoxMap["cleanTime"] = ui->spinBox_38;
}
para_settings::para_settings(QWidget* parent) : QWidget(parent), ui(new Ui::para_settings)
{
    ui->setupUi(this);
    initMappings();
    ui->tb_meter->setText("⚙️ 系统设置");
    ui->tb_cs->setText("🎛️ 仪表参数");
    ui->stackedWidget1->setCurrentIndex(0);
    init_hour_buttons();
    init_quality_spinbox();
    initDeviceParameterWidgets();
}

para_settings::~para_settings() { delete ui; }
void para_settings::init_hour_buttons()
{
    auto targetGroupBox = ui->groupBox_8;
    QGridLayout* gridLayout = qobject_cast<QGridLayout*>(targetGroupBox->layout());
    if (!gridLayout) {
        gridLayout = new QGridLayout(targetGroupBox);
    }
    gridLayout->setHorizontalSpacing(10);
    gridLayout->setVerticalSpacing(10);
    gridLayout->setContentsMargins(15, 15, 15, 15);

    // 在创建新按钮之前，先清理旧按钮
    for (QPushButton* button : m_hourButtons) {
        if (button) {
            button->deleteLater();  // 安全删除Qt对象
        }
    }
    m_hourButtons.clear();
    System* system = System::instance();
    for (int i = 0; i < 24; ++i) {
        QPushButton* button = new QPushButton(QStringLiteral("%1点").arg(i, 2, 10, QChar('0')));
        button->setCheckable(true);
        button->setChecked(system->isScheduled(i));
        button->setFixedSize(40, 30);
        button->setStyleSheet(
            "QPushButton {"
            "    background-color: #37474F;"
            "    border: none;"       /* 去掉边框，更扁平 */
            "    border-radius: 5px;" /* 圆角稍大一些 */
            "    color: #78909C;"     /* 深灰色文字 */
            "    font-weight: bold;"
            "}"
            "QPushButton:checked {"
            "    background-color: #4CAF50;"
            "    color: white;"
            "}"
            "QPushButton:hover {"
            "    background-color: #37474F;"
            "    font-size: 14px;"
            "}"
            "QPushButton:checked:hover {"
            "    background-color: #4CAF50"
            "}");

        int row = i / 6;
        int col = i % 6;
        gridLayout->addWidget(button, row, col);
        m_hourButtons.append(button);
    }
    gridLayout->addWidget(new QLabel(""), 4, 0);
    // 创建功能按钮
    QPushButton* oddButton = new QPushButton("奇数点");
    QPushButton* evenButton = new QPushButton("偶数点");
    QPushButton* selectAllButton = new QPushButton("全选");
    QPushButton* deselectAllButton = new QPushButton("取消全选");
    QPushButton* saveButton = new QPushButton("保存");
    // 功能按钮的布局
    QHBoxLayout* functionalButtonsLayout = new QHBoxLayout();
    functionalButtonsLayout->setSpacing(10);
    functionalButtonsLayout->addWidget(oddButton);
    functionalButtonsLayout->addWidget(evenButton);
    functionalButtonsLayout->addWidget(selectAllButton);
    functionalButtonsLayout->addWidget(deselectAllButton);
    functionalButtonsLayout->addStretch(1);
    functionalButtonsLayout->addStretch(1);
    functionalButtonsLayout->addWidget(saveButton);
    gridLayout->addLayout(functionalButtonsLayout, 5, 0, 1, 6);
    connect(
        oddButton, &QPushButton::clicked, this,
        [this]() {
            for (int i = 0; i < m_hourButtons.size(); ++i) {
                // 小时是从按钮文字 "00点" 中提取的
                int hour = m_hourButtons[i]->text().left(2).toInt();
                m_hourButtons[i]->setChecked(hour % 2 != 0);
            }
        },
        Qt::UniqueConnection);

    connect(
        evenButton, &QPushButton::clicked, this,
        [this]() {
            for (int i = 0; i < m_hourButtons.size(); ++i) {
                int hour = m_hourButtons[i]->text().left(2).toInt();
                m_hourButtons[i]->setChecked(hour % 2 == 0);
            }
        },
        Qt::UniqueConnection);

    connect(selectAllButton, &QPushButton::clicked, this, [this]() {
        for (QPushButton* button : m_hourButtons) {
            button->setChecked(true);
        }
    });

    connect(
        deselectAllButton, &QPushButton::clicked, this,
        [this]() {
            for (QPushButton* button : m_hourButtons) {
                button->setChecked(false);
            }
        },
        Qt::UniqueConnection);

    connect(
        saveButton, &QPushButton::clicked, this,
        [this, system]() {
            int scheduled = 0;
            QStringList selectedHours;
            for (QPushButton* button : m_hourButtons) {
                if (button->isChecked()) {
                    scheduled |= 1 << button->text().left(2).toInt();
                    selectedHours.append(button->text());
                }
            }
            for (int i = 0; i < selectedHours.size() - 1; ++i) {
                int hour1 = selectedHours[i].left(2).toInt();
                int hour2 = selectedHours[i + 1].left(2).toInt();
                if (hour2 - hour1 < 2) {  // 相隔时间需大于2小时
                    QMessageBox::warning(this, "错误", "相隔时间需大于2小时");
                    return;
                }
            }
            SystemConfig config = system->getConfig();
            config.scheduled = scheduled;
            if (system->setConfig(config)) {
                showSuccess("定时测量时间已成功保存，选中的时间点:\n" + selectedHours.join(", "));
            } else {
                QMessageBox::warning(this, "保存", "保存失败");
            }
        },
        Qt::UniqueConnection);
}
void para_settings::init_quality_spinbox()
{
    System* system = System::instance();
    SystemConfig config = system->getConfig();
    m_spinBoxMap["zeroCheckIntervalDays"]->setValue(config.zeroCheckIntervalDays);
    m_spinBoxMap["zeroCheckTime"]->setValue(config.zeroCheckTime);
    m_spinBoxMap["stdCheckIntervalDays"]->setValue(config.stdCheckIntervalDays);
    m_spinBoxMap["stdCheckTime"]->setValue(config.stdCheckTime);
    m_spinBoxMap["calibIntervalDays"]->setValue(config.calibIntervalDays);
    m_spinBoxMap["calibTime"]->setValue(config.calibTime);
    m_spinBoxMap["spikeRecoveryIntervalDays"]->setValue(config.spikeRecoveryIntervalDays);
    m_spinBoxMap["spikeRecoveryTime"]->setValue(config.spikeRecoveryTime);
    m_spinBoxMap["cleanIntervalDays"]->setValue(config.cleanIntervalDays);
    m_spinBoxMap["cleanTime"]->setValue(config.cleanTime);
}
void para_settings::on_tb_meter_clicked() { ui->stackedWidget1->setCurrentIndex(0); }
void para_settings::on_tb_cs_clicked() { ui->stackedWidget1->setCurrentIndex(1); }
void para_settings::on_pb_period_sava_clicked()
{
    System* system = System::instance();
    SystemConfig config = system->getConfig();
    config.zeroCheckIntervalDays = m_spinBoxMap["zeroCheckIntervalDays"]->value();
    config.zeroCheckTime = m_spinBoxMap["zeroCheckTime"]->value();
    config.stdCheckIntervalDays = m_spinBoxMap["stdCheckIntervalDays"]->value();
    config.stdCheckTime = m_spinBoxMap["stdCheckTime"]->value();
    config.calibIntervalDays = m_spinBoxMap["calibIntervalDays"]->value();
    config.calibTime = m_spinBoxMap["calibTime"]->value();
    config.spikeRecoveryIntervalDays = m_spinBoxMap["spikeRecoveryIntervalDays"]->value();
    config.spikeRecoveryTime = m_spinBoxMap["spikeRecoveryTime"]->value();
    config.cleanIntervalDays = m_spinBoxMap["cleanIntervalDays"]->value();
    config.cleanTime = m_spinBoxMap["cleanTime"]->value();

    // 尝试保存配置，业务层会进行验证
    if (system->setConfig(config)) {
        showSuccess("质控周期设置已成功保存");
    } else {
        // 如果保存失败，检查是否是时间冲突
        if (!system->checkConfigTimeConflict(config)) {
            QMessageBox::warning(this, "保存",
                                 "保存失败：存在时间冲突，请检查各项任务的执行时间设置");
        } else {
            QMessageBox::warning(this, "保存", "保存失败");
        }
    }
}

void para_settings::setSaveButtonEnabled(bool enabled) { ui->pb_period_sava->setEnabled(enabled); }
void para_settings::initDeviceParameterWidgets()
{
    // 清理现有的组件
    m_deviceWidgets.clear();

    // 获取第二页的布局
    QWidget* instrumentPage = ui->stackedWidget1->widget(1);  // page索引为1
    if (instrumentPage) {
        QGridLayout* pageLayout = qobject_cast<QGridLayout*>(instrumentPage->layout());
        if (pageLayout) {
            DeviceManager* deviceManager = DeviceManager::instance();
            int row = 0, col = 0;
            for (const QString& deviceName : DEVICE_NAMES) {
                IDevice* device = deviceManager->getDeviceHelper(deviceName);
                if (device && !device->getConfigMap().isEmpty()) {
                    // 创建设备参数组件
                    DeviceParameterWidget* widget = new DeviceParameterWidget(
                        deviceName, device->getConfigMap(), instrumentPage);

                    // 连接信号
                    connect(widget, &DeviceParameterWidget::parametersChanged, this,
                            &para_settings::onDeviceParametersChanged);

                    // 添加到页面布局
                    pageLayout->addWidget(widget, row, col);
                    m_deviceWidgets[deviceName] = widget;

                    // 计算下一个位置（2列布局）
                    col++;
                    if (col >= 2) {
                        col = 0;
                        row++;
                    }
                }
            }

            // 设置布局属性
            pageLayout->setSpacing(10);
            pageLayout->setContentsMargins(10, 10, 10, 10);
        }
    }
}

void para_settings::onDeviceParametersChanged(const QString& deviceName,
                                              const QVariantMap& configValues)
{
    // 获取设备管理器
    DeviceManager* deviceManager = DeviceManager::instance();
    IDevice* device = deviceManager->getDeviceHelper(deviceName);

    if (device) {
        // 保存设备配置
        if (device->saveDeviceConfig(configValues)) {
            showSuccess(QString("%1 设备参数已成功保存").arg(deviceName));
        } else {
            QMessageBox::warning(this, "保存失败", QString("保存 %1 设备参数失败").arg(deviceName));
        }
    }
}

void para_settings::updateDeviceConfigValues()
{
    // 更新所有设备的配置值
    DeviceManager* deviceManager = DeviceManager::instance();
    for (const QString& deviceName : DEVICE_NAMES) {
        IDevice* device = deviceManager->getDeviceHelper(deviceName);
        if (device && !device->getConfigMap().isEmpty()) {
            auto configValues = device->getConfigMap();
            if (m_deviceWidgets.contains(deviceName)) {
                m_deviceWidgets[deviceName]->updateConfigValues(configValues);
            }
        }
    }
}
void para_settings::showEvent(QShowEvent* event)
{
    QWidget::showEvent(event);
    setSaveButtonEnabled(user::isLoggedIn());
    init_hour_buttons();
    init_quality_spinbox();
    updateDeviceConfigValues();
}